package com.gurun.codes.business.human_body;

import android.content.Context;
import android.text.TextUtils;

import com.gurun.codes.App;
import com.gurun.codes.R;
import com.gurun.codes.contract.base.BaseAlarmListPresenter;
import com.gurun.codes.contract.base.view.RxView;
import com.gurun.codes.utils.Constants;
import com.gurun.model.base.ResultObserver;
import com.gurun.model.base.RetrofitManager;
import com.gurun.model.bean.ApiResult;
import com.gurun.model.bean.common.GetDeviceAlarmInfoListResultBean;
import com.gurun.model.bean.door_window.GetDoorWindowInfoRequestBean;
import com.gurun.model.bean.door_window.GetDoorWindowInfoResultBean;
import com.gurun.model.bean.human_body.GetHumanInfoRequestBean;
import com.gurun.model.bean.human_body.GetHumanInfoResultBean;
import com.gurun.model.service.DoorWindowService;
import com.gurun.model.service.HumanBodyService;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;

public interface HumanBodyActivityContract {

    interface HumanBodyActivityView extends RxView {

        void onLoading();

        void onLoaded(GetHumanInfoResultBean datas);

        void onError(String msg);

        void onComplete();

        void resetListDatas();
    }

    class HumanBodyActivityViewPresenter extends BaseAlarmListPresenter<HumanBodyActivityView> {

        private Context mContext;

        private String mLastRefreshTime;//最后刷新时间
        private static int TOTAL_COUNTER = 0;//服务器端一共多少条数据
        private static int mPageCount = 0;
        private int mCurrentPage = 1;//当前页

        @Override
        protected void onMLoading() {

        }

        @Override
        protected void onMLoaded(GetDeviceAlarmInfoListResultBean datas) {

        }

        @Override
        protected void onMError(String msg) {

        }

        @Override
        protected void onMComplete() {

        }

        @Override
        protected void mResetListDatas() {

        }

        private String getRefreshTime() {
            if (TextUtils.isEmpty(mLastRefreshTime)) {
                mLastRefreshTime = "0";
            }
            return mLastRefreshTime;
        }

        private void setRefreshTime(String currentTime) {
            mLastRefreshTime = currentTime;
        }

        public HumanBodyActivityViewPresenter(Context context) {
            this.mContext = context;
        }

        public void getHUmanBodyInfo(long deviceId,int timeFlag) {
            GetHumanInfoRequestBean requestBean = new GetHumanInfoRequestBean();
            requestBean.setVersion(Constants.HTTP_VERSION);
            requestBean.setUserId(App.getInstance().getLoginUserId());
            requestBean.setToken(App.getInstance().getLoginToken());
            requestBean.setPageNo(mCurrentPage);
            requestBean.setPageSize(Constants.PAGE_SIZE);
            requestBean.setRefreshTime(getRefreshTime());
            requestBean.setDeviceId(deviceId);
            requestBean.setTimeFlag(timeFlag);

            RetrofitManager.getInstance().createApiService(HumanBodyService.class)
                    .getHumanbodyInfo(requestBean)
                    .compose(getView().<GetHumanInfoResultBean>bindToLifecycleDestroy())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe((new ResultObserver<GetHumanInfoResultBean>() {

                        @Override
                        public void onLoading(Disposable d) {
                            getView().onLoading();
                        }

                        @Override
                        public void onOtherError(Throwable e) {
                            getView().onError(mContext.getString(R.string.common_connect_server_failed));
                        }

                        @Override
                        public void onLoaded() {
                            getView().onComplete();
                        }

                        @Override
                        public void onSuccess(GetHumanInfoResultBean result, String msg) {
                            if (result != null) {
                                if (mCurrentPage == 1) {
                                    getView().resetListDatas();
                                }
                                TOTAL_COUNTER = result.getTotalCount();
                                mPageCount = result.getPageCount();

                                if (result.getAlarmList() != null && result.getAlarmList().size() > 0) {
                                    getView().onLoaded(result);
                                    mCurrentPage++;
                                    setRefreshTime(result.getRefreshTime());
                                }
                            }
                        }

                        @Override
                        public void onApiError(ApiResult result) {
                            if (result != null) {
                                getView().onError(result.getRetMsg());
                            } else {
                                getView().onError(mContext.getString(R.string.common_connect_server_failed));
                            }
                        }
                    }));
        }

        /**
         * 页面上点击下一页or上一页取数据,从mFinalDatas一页一页的取，如果最后一页不足一页的数据，就判断是否需要从服务器获取数据，如果需要
         * 就先从服务器获取，然后在返回给页面
         *
         * @param isNextPage true：下一页
         * @param isPrePage  true：上一页
         *                   除了上一页和下一页就是获取当前页：比如说第一次获取和从服务器返回后自动获取
         */
        public List<Object> getDatas(boolean isNextPage, boolean isPrePage, long deviceId) {
            if (isNextPage) {
                mCurrentPageForLocal += 1;
            }
            if (isPrePage) {
                mCurrentPageForLocal -= 1;
            }

            if (mCurrentPageForLocal < 1) {
                mCurrentPageForLocal = 1;
            }

            List<Object> pageDatas = new ArrayList<>();
            int startIndex = (mCurrentPageForLocal - 1) * PAGE_SIZE;
            int endIndex = startIndex + PAGE_SIZE - 1;
            int currentDatasCount = mFinalDatas.size();
            if (currentDatasCount < (endIndex + 1)) {//不足一页，就去服务器获取
                if (mCurrentPage >= mPageCount) {//已经将服务器数据获取完
                    if (currentDatasCount >= (startIndex + 1)) {//如果最后一页还有数据，即使不足一页
                        endIndex = currentDatasCount - 1;
                    } else {//已经没有数据了,返回null
                        if (isNextPage) {
                            mCurrentPageForLocal -= 1;//将页码回归
                        }
                        return null;
                    }
                } else {
                    getHUmanBodyInfo(deviceId,3);
                    return pageDatas;//返回一个size为0的list说明去服务器获取数据了
                }
            }

            for (int i = startIndex; i <= endIndex; i++) {
                pageDatas.add(mFinalDatas.get(i));
            }
            return pageDatas;
        }

        public void getHUmanBodyInfoForChart(long deviceId,int timeFlag) {
            GetHumanInfoRequestBean requestBean = new GetHumanInfoRequestBean();
            requestBean.setVersion(Constants.HTTP_VERSION);
            requestBean.setUserId(App.getInstance().getLoginUserId());
            requestBean.setToken(App.getInstance().getLoginToken());
            requestBean.setPageNo(1);
            requestBean.setPageSize(1000);
            requestBean.setRefreshTime("0");
            requestBean.setDeviceId(deviceId);
            requestBean.setTimeFlag(timeFlag);

            RetrofitManager.getInstance().createApiService(HumanBodyService.class)
                    .getHumanbodyInfo(requestBean)
                    .compose(getView().<GetHumanInfoResultBean>bindToLifecycleDestroy())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe((new ResultObserver<GetHumanInfoResultBean>() {

                        @Override
                        public void onLoading(Disposable d) {
                            getView().onLoading();
                        }

                        @Override
                        public void onOtherError(Throwable e) {
                            getView().onError(mContext.getString(R.string.common_connect_server_failed));
                        }

                        @Override
                        public void onLoaded() {
                            getView().onComplete();
                        }

                        @Override
                        public void onSuccess(GetHumanInfoResultBean result, String msg) {
                            if (result != null) {
                                if (mCurrentPage == 1) {
                                    getView().resetListDatas();
                                }
                                TOTAL_COUNTER = result.getTotalCount();
                                mPageCount = result.getPageCount();

                                if (result.getAlarmList() != null && result.getAlarmList().size() > 0) {
                                    getView().onLoaded(result);
//                                    mCurrentPage++;
//                                    setRefreshTime(result.getRefreshTime());
                                }
                            }
                        }

                        @Override
                        public void onApiError(ApiResult result) {
                            if (result != null) {
                                getView().onError(result.getRetMsg());
                            } else {
                                getView().onError(mContext.getString(R.string.common_connect_server_failed));
                            }
                        }
                    }));
        }
    }

}
